//
//  CountDownViewController.m
//  TotalDemo
//
//  Created by gujian on 16/2/14.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "CountDownViewController.h"
#import "TDViewUtils.h"

@interface CountDownViewController()

@property (nonatomic, weak) UILabel *countTimeLbl;

@property (nonatomic, weak) UIButton *startBtn;

@property (nonatomic, weak) UIButton *stopBtn;

@property (nonatomic, weak) UIButton *resetBtn;

@property (nonatomic, assign) BOOL isReset;

@property (nonatomic, weak) NSTimer *timer;

@property (nonatomic, assign) NSTimeInterval totalTime;

@end

@implementation CountDownViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"倒计时";
    [self setupViews];
    [self initData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNotificaion];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


- (void)setupViews
{
    UILabel *lbl = [TDViewUtils createCustomLabel];
    lbl.textAlignment = NSTextAlignmentLeft;
    lbl.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    [self.view addSubview:lbl];
    self.countTimeLbl = lbl;
    
    UIButton *btn = [TDViewUtils createCustomButton];
    btn.frame = CGRectMake(SCREEN_WIDTH/2.0 - 130/2.0, lbl.bottom+10, 50, 38);
    [btn setTitle:@"开始" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(startCountDown) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.startBtn = btn;

    UIButton *stopBtn = [TDViewUtils createCustomButton];
    stopBtn.frame = CGRectMake(btn.right+20, CGRectGetMaxY(lbl.frame)+10, 50, 38);
    [stopBtn setTitle:@"暂停" forState:UIControlStateNormal];
    [stopBtn addTarget:self action:@selector(pauseCountDown) forControlEvents:UIControlEventTouchUpInside];
    stopBtn.enabled = NO;
    [self.view addSubview:stopBtn];
     self.stopBtn = stopBtn;

    UIButton *resetBtn = [TDViewUtils createCustomButton];
    resetBtn.frame = CGRectMake(SCREEN_WIDTH/2.0 - 50/2.0, stopBtn.bottom+10, 50, 38);
    [resetBtn setTitle:@"重置" forState:UIControlStateNormal];
    [resetBtn addTarget:self action:@selector(resetCountDown) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:resetBtn];
    self.resetBtn = resetBtn;
    
    
}

- (void)initData
{
    self.isReset = YES;
}

- (void)startCountDown
{
    [self stopCountDown];
    
    if (self.isReset) {
        self.totalTime = [[NSDate date] timeIntervalSince1970] + 10;
    }
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(update) userInfo:nil repeats:YES];
    self.timer = timer;
    
    self.startBtn.enabled = NO;
    self.stopBtn.enabled = YES;
}

- (void)stopCountDown
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)resetCountDown
{
    [self stopCountDown];
    
    self.isReset = YES;
    self.startBtn.enabled = YES;
    self.stopBtn.enabled = NO;
    
    self.countTimeLbl.text = @"";
}

- (void)pauseCountDown
{
   [self stopCountDown];
    
    NSTimeInterval leftInterval = self.totalTime - [[NSDate date] timeIntervalSince1970];
    
    if (leftInterval <= 0) {
        leftInterval = 0;
    }
    
    self.isReset = NO;
    self.totalTime = [[NSDate date] timeIntervalSince1970] + leftInterval;
    self.startBtn.enabled = YES;
    self.stopBtn.enabled = NO;
}

- (void)update
{
    NSTimeInterval leftInterval = self.totalTime - [[NSDate date] timeIntervalSince1970];
    
    if (leftInterval <= 0) {
        leftInterval = 0;
        self.countTimeLbl.text = @"00:00:00:00";
        [self stopCountDown];
        return;
    }
    
    NSInteger totalSeconds = (NSInteger)leftInterval;
    NSInteger hour = totalSeconds/3600;
    NSInteger min = (totalSeconds/60)%60;
    NSInteger sec = totalSeconds%60;
    CGFloat msec = leftInterval - totalSeconds;
    
    NSMutableString *timeStr = [[NSMutableString alloc] init];
    
    if (hour) {
        [timeStr appendFormat:@"%02d:",(int)hour];
    }
    
    [timeStr appendFormat:@"%02d:",(int)min];
    [timeStr appendFormat:@"%02d:",(int)sec];
    [timeStr appendFormat:@"%02d",(int)(msec * 1000)];
    
    self.countTimeLbl.text = timeStr;
}

- (void)addNotificaion
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground:) name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)applicationEnterBackground:(NSNotification *)noti
{
    NSTimeInterval leftInterval = self.totalTime - [[NSDate date] timeIntervalSince1970];
    NSTimeInterval totalTime = self.totalTime;
    
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.totalDemoShareDefaults"];
    [userDefaults setInteger:leftInterval forKey:@"goup.totalDemoShareDefaults.left"];
    [userDefaults setInteger:totalTime forKey:@"group.totalDemoShareDefaults.total"];
    [userDefaults synchronize];
}

- (void)removeNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)dealloc
{
    [self stopCountDown];
    [self removeNotification];
}

@end
